package com.sky.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.user.MerchatMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.*;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private static final String url = "https://api.weixin.qq.com/sns/jscode2session" ;

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private MerchatMapper merchatMapper;

    @Override
    public UserLoginVO login(UserLoginDTO userDto) {
        //微信用户登录自动注册
        // 调用方法获取到openId
        String openId = getUserOpenId(userDto.getCode());
        //判断一下
        if(!StringUtils.hasText(openId)){
            throw new BaseException("未获取到openId");
        }
        //根据openId 去数据库里找，是否存在，
        User user = userMapper.getByOpenId(openId);
        // 不存在就注册 添加数据到数据库
        if(user == null){
            user = new User();
            user.setCreateTime(LocalDateTime.now());
            user.setOpenid(openId);
            userMapper.insert(user);
        }
        //生成token
        HashMap<String, Object> param = new HashMap<>();
        param.put("openId",openId);
        param.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),param);
        //把结果补满
        Merchant merchant = merchatMapper.search(1);
        //返回结果 使用@Build 注解

        //计算配送费
        String merchantLocation = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(merchantLocation, userDto.getLocation());

        UserLoginVO loginVO = UserLoginVO.builder().token(token)
                .shopTelephone("")
                .shopName(merchant.getShopName())
                .shopAddress(merchant.getShopAddress())
                .deliveryFee(delivoryCost)
                .shopId(merchant.getId())
                .openid(openId)
                .deliveryFee(delivoryCost)
                .build();
        return loginVO;
    }


  /*  @Override
    public void addAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        userMapper.addAddressBook(addressBook);
    }

    *//**
     * 查询用户的所有地址
     * @return
     *//*
    @Override
    public List<AddressBook> selectAddreeBoodList() {

        List<AddressBook> list = userMapper.selectAddreeBoodList(BaseContext.getCurrentId());

        return list;
    }

    @Override
    public void updateAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        userMapper.updateAddressBook(addressBook,addressBook.getId());
    }

    @Override
    public void deleteAddressBook(int id) {
        userMapper.deleteAddressBook(id);
    }

    @Override
    public AddressBook selectAddressById(Long id) {
        Long  userId = BaseContext.getCurrentId();
        AddressBook addressBook = userMapper.selectAddressById(id,userId);
        return addressBook;
    }

    @Override
    public AddressBook selectDefault() {
        Long  userId = BaseContext.getCurrentId();
        AddressBook addressBook = userMapper.selectDefalut(userId);
        return addressBook;
    }*/

    /**
     * 获取openId
     * @param code
     * @return
     */
    private String getUserOpenId(String code){
        Map<String,String> param = new HashMap<>();
        param.put("appid" ,weChatProperties.getAppid());
        param.put("secret",weChatProperties.getSecret());
        param.put("js_code",code);
        param.put("grant_type","authorization_code");

        log.info("获取到的appid为{}",weChatProperties.getAppid());
        log.info("获取到的secret为{}",weChatProperties.getSecret());


        String response = HttpClientUtil.doGet(url, param);
        log.info("获取到的微信登录返回为：{}",response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String openId = (String) jsonObject.get("openid");
        return openId;
    }
}
